package com.test.reactor.mq.rocket;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Configuration
@ConfigurationProperties(prefix="rocketmq.producer")
@Slf4j
@Data
public class RocketMQProducer {
	
    private String groupName;
    
    private String namesrvAddr;
    
    private String instanceName;
    
    private String topic;
    private int maxMessageSize;
    
    private int sendMsgTimeout;

    @Autowired
    TransactionCheckListenerImpl transactionListener;
    
    @Bean(name = "producer")
    public DefaultMQProducer getRocketMQProducer() {
       
    	DefaultMQProducer producer = new DefaultMQProducer(groupName);
        producer.setNamesrvAddr(namesrvAddr);
        producer.setInstanceName(instanceName);
        producer.setMaxMessageSize(maxMessageSize);
        producer.setSendMsgTimeout(sendMsgTimeout);
        producer.setVipChannelEnabled(false);
        try {
            producer.start();
            log.info("rocketMQ is start !!groupName : {},nameserAddr:{}",groupName,namesrvAddr);
        } catch (MQClientException e) {
            log.error(String.format("rocketMQ start error,{}",e.getMessage()));
            e.printStackTrace();
        }
        return producer;
    }
    @Bean(name = "tproducer")
    public TransactionMQProducer getTransactionMQProducer() {
       
    	TransactionMQProducer tproducer = new TransactionMQProducer(groupName+"t");
    	tproducer.setNamesrvAddr(namesrvAddr);
    	tproducer.setInstanceName(instanceName);
    	tproducer.setMaxMessageSize(maxMessageSize);
    	tproducer.setSendMsgTimeout(sendMsgTimeout);
    	tproducer.setVipChannelEnabled(false);
        try {
        	tproducer.setTransactionListener(transactionListener);
        	tproducer.start();
            log.info("rocketMQ Transaction is start !!groupName : {},nameserAddr:{}",groupName,namesrvAddr);
        } catch (MQClientException e) {
            log.error(String.format("rocketMQ start error,{}",e.getMessage()));
            e.printStackTrace();
        }
        return tproducer;
    }
}
